package com.debao.system.service.impl;

import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.domain.entity.SysUser;
import com.debao.common.enums.GoodsOrderStatus;
import com.debao.common.model.TempData;
import com.debao.common.model.WechatTemplateVo;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.domain.Goods;
import com.debao.system.service.IConfigService;
import com.debao.system.service.IGoodsService;
import com.debao.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.debao.system.mapper.GoodsOrderMapper;
import com.debao.system.domain.GoodsOrder;
import com.debao.system.service.IGoodsOrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品订单Service业务层处理
 *
 * @author DeBao
 * @date 2024-06-13
 */
@Service
@Slf4j
public class GoodsOrderServiceImpl implements IGoodsOrderService {
    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IConfigService configService;



    /**
     * 商品下单订阅通知模板Id
     */
    private static final String templateId = "Ki0iDvZupFktBmxV8LgMKu0XcOGqCjSyaHIKY0j1KpA";

    /**
     * 查询商品订单
     *
     * @param id 商品订单主键
     * @return 商品订单
     */
    @Override
    public GoodsOrder selectGoodsOrderById(Long id) {
        return goodsOrderMapper.selectGoodsOrderById(id);
    }

    /**
     * 根据订单号查询
     *
     * @param orderNo
     * @return
     */
    @Override
    public GoodsOrder selectGoodsOrderByOrderNo(String orderNo) {
        return goodsOrderMapper.selectGoodsOrderByorderNo(orderNo);
    }

    /**
     * 查询商品订单列表
     *
     * @param goodsOrder 商品订单
     * @return 商品订单
     */
    @Override
    public List<GoodsOrder> selectGoodsOrderList(GoodsOrder goodsOrder) {
        return goodsOrderMapper.selectGoodsOrderList(goodsOrder);
    }

    /**
     * 新增商品订单
     *
     * @param goodsOrder 商品订单
     * @return 结果
     */
    @Override
    public int insertGoodsOrder(GoodsOrder goodsOrder) {
        return goodsOrderMapper.insertGoodsOrder(goodsOrder);
    }

    /**
     * 修改商品订单
     *
     * @param goodsOrder 商品订单
     * @return 结果
     */
    @Override
    public int updateGoodsOrder(GoodsOrder goodsOrder) {
        return goodsOrderMapper.updateGoodsOrder(goodsOrder);
    }

    /**
     * 批量删除商品订单
     *
     * @param ids 需要删除的商品订单主键
     * @return 结果
     */
    @Override
    public int deleteGoodsOrderByIds(Long[] ids) {
        return goodsOrderMapper.deleteGoodsOrderByIds(ids);
    }

    /**
     * 删除商品订单信息
     *
     * @param id 商品订单主键
     * @return 结果
     */
    @Override
    public int deleteGoodsOrderById(Long id) {
        return goodsOrderMapper.deleteGoodsOrderById(id);
    }

    /**
     * 处理支付成功回调
     *
     * @param orderNo
     * @param transactionId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public void paySucHandleOrder(String orderNo, String transactionId) {
        if (StringUtils.isBlank(orderNo)) {
            log.error("订单回调更新数据失败, orderNo为空");
            return;
        }
        String logHead = String.format("订单回调更新, orderNo = %s ", orderNo);
        // 获取商品订单信息
        GoodsOrder order = goodsOrderMapper.selectGoodsOrderByorderNo(orderNo);
        if (Objects.isNull(order)) {
            // todo 自定义异常类
            log.error(logHead + "订单不存在");
            return;
        }
        if (!StringUtils.equalsIgnoreCase(order.getStatus(), String.valueOf(GoodsOrderStatus.None))) {
            log.error(logHead + "订单信息回调已更新 status = {}", order.getStatus());
            return;
        }
        // 更新订单状态 【支付成功】
        order.setTransactionId(transactionId);
        order.setPayMoney(order.getMoney());
        order.setPayAt(new Date());
        order.setStatus(String.valueOf(GoodsOrderStatus.Paid));
        int row = goodsOrderMapper.updateGoodsOrder(order);
        if (row != 1) {
            log.error(logHead + "数据更新失败");
        }
        //消息推送
        if (row == 1) {
            Goods goods = goodsService.selectGoodsById(order.getGoodsId());
            //异步方式实现短信推送 通知给平台
            Thread threadMsg = new Thread(() -> {
                synchronized (this) {
                    //获取平台官方手机号码
                    try {
                        String phone = configService.selectValueByKey(WechatConstants.OFFICIAL_PHONE);
                        SysUser sysUser = userService.selectUserById(order.getUserId());
                        if (!phone.isEmpty()) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("name", sysUser.getNickName());
                            map.put("shName", goods.getName());
                            AliyunSmsUtil.sendSms(phone, "SMS_471730016", JSONObject.toJSONString(map));
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    //订阅消息通知 通知给下单的用户
                    String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
                    //获取用户openid
                    String openId = userService.getOpenIdByUserId(order.getUserId());
                    if (openId.isEmpty()) {
                        return;
                    }
                    Map<String, TempData> data = new HashMap<>();
                    data.put("character_string6", new TempData(orderNo));
                    data.put("thing2", new TempData(goods.getName()));
                    data.put("amount3", new TempData((order.getMoney() / 100L) + "元"));
                    data.put("time7", new TempData(order.getPayAt().toString()));
                    WechatUtils.postTemplateData(new WechatTemplateVo().setTemplateId(templateId).setToken(token).setOpenid(openId).setData(data).setPage("/subPackages/order/details/order_detail?orderNo=" + orderNo));
                }
            });
            threadMsg.start();
        }
    }


    /**
     * 是否支付成功
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean isPaySuccess(String orderNo) {
        return goodsOrderMapper.isPaySuccess(orderNo);
    }


}
